package com.xxr.mom.ci.charging.dynamic;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 多数据源配置
 * @author natsuki_kining
 */
@Log4j2
@Configuration
public class DataSourceConfig {

    @Bean("ciChargingServiceDataSource")
    @ConfigurationProperties("spring.datasource.ci-charging-service.hikari")
    public DataSource ciChargingServiceDataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean("ciChargingDeviceDataSource")
    @ConfigurationProperties("spring.datasource.ci-charging-device.hikari")
    public DataSource ciChargingDeviceDataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean("ciChargingBillDataSource")
    @ConfigurationProperties("spring.datasource.ci-charging-bill.hikari")
    public DataSource ciChargingBillDataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean
    @Primary
    public DataSource multipleDataSource(
            @Qualifier("ciChargingServiceDataSource") DataSource ciChargingServiceDataSource,
            @Qualifier("ciChargingDeviceDataSource") DataSource ciChargingDeviceDataSource,
            @Qualifier("ciChargingBillDataSource") DataSource ciChargingBillDataSource
    ) {
        RoutingDataSource routingDataSource = new RoutingDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceEnum.CI_CHARGING_SERVICE.getDbName(), ciChargingServiceDataSource);
        targetDataSources.put(DataSourceEnum.CI_CHARGING_DEVICE.getDbName(), ciChargingDeviceDataSource);
        targetDataSources.put(DataSourceEnum.CI_CHARGING_BILL.getDbName(), ciChargingBillDataSource);
        routingDataSource.setTargetDataSources(targetDataSources);
        routingDataSource.setDefaultTargetDataSource(ciChargingServiceDataSource);
        return routingDataSource;
    }
}
